/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: AlarmClient.cpp,v 1.8 2009-10-26 12:47:01 morsko Exp $
 *
 * \file
 * \brief Implementation for Alarm interface client library.
 * \author Antti Maula <antti.maula@tkk.fi>
 */

#include "AlarmClient.hpp"
#include "AlarmData.hpp"

//*****************************************************************************
using namespace MaCI::Alarm;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CAlarmClient::CAlarmClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(2,1),
    CThread(1),
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_ALARM, aInterfaceMinor),
    iAlarmSequence(0),
    iAlarmDataArray(),
    iAlarmClientCallback(NULL)
{
  dPrint(4,"CAlarmClient %p constructed", this);
}
//*****************************************************************************

CAlarmClient::~CAlarmClient()
{
  DoClose();
  dPrint(4,"CAlarmClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CAlarmClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();
    iGIMIPtr->setQueueMaxSize(GIMI_PROTOCOL_MACI_ALARM, iInterfaceMinor, 100);
    //    RegisterAcceptedService("MaCI-AlarmClient-CmdReplies; '" + iServiceDescription + "'");

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      CThread::RunThread();
      dPrint(4,"CAlarmClient::DoOpen() was succesfull.");
    } else {
      dPrint(3,"Failed to subscribe to MaCI::Alarm service!");
    }

  } else {
    dPrint(4,"AlarmClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CAlarmClient::DoClose(void)
{


  MaCI::EMaCIError result = MaCI::KMaCIError;
  //dPrint(ODTEST, "%p - CAlarmClient::DoClose() called", this);
  
  if (CThread::IsThreadRunning()) {
    // Deactivate
    //dPrint(ODTEST,"Deactivate");
    CMaCI::SetActive(false);

    // Unsub
    //    dPrint(ODTEST,"UnSub");
    UnsubscribeToInterface(TimeoutValue(2000));

    // Wait for thread to complete.
    //    dPrint(ODTEST,"Notify");
    CSync::Notify(KEventAlarmData);
   
    //    dPrint(ODTEST,"Wait");
    CThread::WaitThread();
   
    //    dPrint(ODTEST,"Wait Completed");

    result = KMaCIOK;
  } else {
    result = MaCI::KMaCIError;
    return result; 
  }
  assert(CThread::IsThreadRunning() == false);

  dPrint(3, "Alarm client succesfully closed");
  return result;
}    
//*****************************************************************************

bool CAlarmClient::GetAlarmEvent(CAlarmData &aData,
                                 const unsigned int aTimeout_ms)
{  
  bool result = false;
  
  // Fallback in case the class is not active.
  if (!IsActive()) return false;

  Lock();
  
  int time_left = aTimeout_ms;
  unsigned int time_begin = ownTime_get_ms();
  
  // The available scan is older than requested - must wait for time_left
  do {
    Wait(time_left, KEventAlarmData);
    time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
    
  } while(IsActive() && 
          iAlarmDataArray.empty() && 
          time_left > 0 );
  
  if (! iAlarmDataArray.empty()) {
    
    aData = iAlarmDataArray.front();
    iAlarmDataArray.pop_front();
    result = true;
    
  } else {
    // No :(
    dPrint(8, "Failed to get AlarmData! (Timeout %dms)",
           aTimeout_ms);
  }
  
  Unlock();
  
  return result;
}
//*****************************************************************************

bool CAlarmClient::SendCommand(const CAlarmData &aAlarmData)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aAlarmData.GetCommand()) {
      // Foo.
      ++iAlarmSequence;
      
      // Send.
      SendInterfaceMessage(aAlarmData.GetBinBagContainerPtr()->GetBuffer(),
                           aAlarmData.GetBinBagContainerPtr()->GetBufferSize(),
                           iAlarmSequence);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d, seq: %d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             iAlarmSequence-1,
             aAlarmData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CAlarmData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send AlarmData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CAlarmClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CAlarmData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as Alarm, now handle contents
      Lock();

      if (id.GetAlarmEvent() != NULL) {
        iAlarmDataArray.push_back(id);
        ++iAlarmSequence;
        Notify(KEventAlarmData);
        
      } else {
        dPrint(2, "Warning: Invalid AlarmData received, doesn't contain AlarmEvent!");

      }
      
      Unlock();
      
      // Call the handler if set.
      if (iAlarmClientCallback) {
        dPrint(8,"Got Callback for AlarmDataEvent - executing!");
        iAlarmClientCallback->OnAlarmDataEvent(id,
                                               iAlarmSequence,
                                               *this);
        dPrint(8,"Callback for AlarmDataEvent - execution complete!");
      } 
      
    } else {
      dPrint(4,"WARNING: Received Alarm interface message, but failed to decode as AlarmData!");
      
    }
  }
  
  return result;
}
//*****************************************************************************

int CAlarmClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
 
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    // e = ReceiveInterfaceMessage(gmsg, 1000*60*60);
    e = ReceiveInterfaceMessage(gmsg, 1000*60*60);
    if (e == KMaCIOK) {
      
      ProcessMessage(gmsg);
      
    } else if (e != KMaCITimeout) {
      if(IsActive()){
        // Other error, try to recover by sleeping one second.
        dPrint(3,"ProcessMessage returned error %u and client still active. Trying to recover by sleeping 1000ms ",
               e);
        ownSleep_ms(1000);
      }else{
        //
        dPrint(3,"ProcessMessage returned error %u. Normal situtation because client is already closed",
               e);
      }
           
    }
  }
  
  //  dPrintLCRed(ODTEST, "GIMIMessage handler stopped (%p)",this);
  //  dPrint(8, "GIMIMessage handler stopped (%p)",this);
  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
